<template>
    <page-container>
        <div class="flex left-right-wrap">
            <div class="left-wrap">
                <left-tree v-model:checked="queryParams.projectCode" @checked="handleTreeCheck"></left-tree>
            </div>
            <div class="right-wrap">
                <div class="ant-pro-table">
                    <div class="ant-pro-table-search">
                        <a-form layout="horizontal">
                            <a-row :gutter="15" type="flex" justify="start" :class="{ expand: expand }">
                                <a-col :xs="12" :sm="12" :md="6" :lg="4">
                                    <a-form-item>
                                        <a-input-search v-model:value="queryParams.orderNum" placeholder="工单编号" allow-clear enter-button @search="handleSearch()" />
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="5">
                                    <a-form-item>
                                        <a-input-search v-model:value="queryParams.nameOrPhone" placeholder="客户姓名/电话" allow-clear enter-button @search="handleSearch()" />
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                    <a-form-item>
                                        <a-select
                                            ref="select"
                                            v-model:value="queryParams.orderType"
                                            placeholder="工单类型"
                                            :options="
                                                Object.keys(typeMap).map(item => ({
                                                    label: typeMap[item],
                                                    value: item,
                                                }))
                                            "
                                            allow-clear
                                            @change="handleSearch()"
                                        ></a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                    <a-form-item>
                                        <a-select
                                            ref="select"
                                            v-model:value="queryParams.orderClassifyId"
                                            placeholder="工单分类"
                                            :options="dictData.cateData"
                                            :field-names="{
                                                label: 'classifyName',
                                                value: 'id',
                                            }"
                                            allow-clear
                                            @change="handleSearch()"
                                        ></a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                    <a-form-item>
                                        <a-select
                                            v-model:value="queryParams.orderProfessionalLine"
                                            placeholder="责任条线"
                                            :options="dictData.txData"
                                            allow-clear
                                            :field-names="{
                                                label: 'name',
                                                value: 'id',
                                            }"
                                            @change="handleSearch()"
                                        ></a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                    <a-form-item>
                                        <a-select
                                            v-model:value="queryParams.spotCheck"
                                            placeholder="抽检状态"
                                            :options="
                                                Object.keys(spotCheckMap).map(item => ({
                                                    label: spotCheckMap[item],
                                                    value: item,
                                                }))
                                            "
                                            allow-clear
                                            @change="handleSearch()"
                                        ></a-select>
                                    </a-form-item>
                                </a-col>
                                <template v-if="expand">
                                    <a-col :xs="12" :sm="12" :md="6" :lg="3">
                                        <a-form-item>
                                            <a-select
                                                v-model:value="queryParams.orderSource"
                                                placeholder="工单来源"
                                                :options="dictData.xmytData"
                                                allow-clear
                                                @change="handleSearch()"
                                            ></a-select>
                                        </a-form-item>
                                    </a-col>
                                    <a-col :xs="12" :sm="12" :md="7" :lg="6">
                                        <a-form-item>
                                            <a-range-picker
                                                v-model:value="queryParams.orderTime"
                                                :placeholder="['提报开始时间', '提报结束时间']"
                                                allow-clear
                                                @change="handleSearch()"
                                            />
                                        </a-form-item>
                                    </a-col>
                                </template>
                                <a-col :xs="24" :sm="24" :md="12" :lg="3">
                                    <!-- <a-button @click="handleSearch" type="primary">搜索</a-button> -->
                                    <a-button @click="handleReset" class="ml-5px">重置</a-button>
                                    <!-- <a-button type="text" class="ml-5px" @click="expand = !expand">
                                        <a-popover :content="expand ? '展开' : '折叠'">
                                            <template v-if="expand">
                                                <UpOutlined />
                                            </template>
                                            <template v-else>
                                                <DownOutlined />
                                            </template>
                                        </a-popover>
                                    </a-button> -->
                                </a-col>
                            </a-row>
                        </a-form>
                    </div>
                    <a-card :body-style="{ padding: 0 }" ref="elRef">
                        <div class="ant-pro-table-list-toolbar">
                            <div class="ant-pro-table-list-toolbar-container">
                                <div class="ant-pro-table-list-toolbar-left">
                                    <!-- <div class="ant-pro-table-list-toolbar-title">查询表格</div> -->
                                </div>
                                <div class="ant-pro-table-list-toolbar-right">
                                    <a-space align="center">
                                        <!-- <a-button type="primary" @click="modalVisible = true" v-permission="[`yfwy:order:create`]">
                                            <plus-outlined />
                                            新建
                                        </a-button> -->
                                        <a-button @click="handleExport" class="ml-10px" :loading="exportLoading" v-permission="[`yfwy:order:export`]">
                                            <download-outlined />
                                            导出
                                        </a-button>
                                        <div class="ant-pro-table-list-toolbar-setting-item">
                                            <a-tooltip title="表格斑马纹">
                                                <a-switch checked-children="开" un-checked-children="关" v-model:checked="fetchDataContext.stripe" />
                                            </a-tooltip>
                                        </div>
                                    </a-space>
                                    <div class="ant-pro-table-list-toolbar-divider">
                                        <a-divider type="vertical" />
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip title="刷新">
                                            <reload-outlined @click="reload" />
                                        </a-tooltip>
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip title="密度">
                                            <a-dropdown :trigger="['click']" placement="bottomRight">
                                                <column-height-outlined />
                                                <template #overlay>
                                                    <a-menu
                                                        style="width: 80px"
                                                        :selected-keys="[state.tableSize]"
                                                        @click="
                                                            ({ key }) => {
                                                                fetchDataContext.tableSize = String(key);
                                                            }
                                                        "
                                                    >
                                                        <a-menu-item key="default">
                                                            <a href="javascript:;">默认</a>
                                                        </a-menu-item>
                                                        <a-menu-item key="middle">
                                                            <a href="javascript:;">中等</a>
                                                        </a-menu-item>
                                                        <a-menu-item key="small">
                                                            <a href="javascript:;">紧凑</a>
                                                        </a-menu-item>
                                                    </a-menu>
                                                </template>
                                            </a-dropdown>
                                        </a-tooltip>
                                    </div>
                                    <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-popover placement="bottomRight" arrowPointAtCenter trigger="click" overlayClassName="ant-pro-table-column-setting-overlay">
                                            <template #title>
                                                <div class="ant-pro-table-column-setting-title">
                                                    <a-checkbox v-model:checked="columnState.checkAll" :indeterminate="columnState.indeterminate" @change="handleColumnAllClick">
                                                        列展示 / 排序
                                                    </a-checkbox>
                                                    <a @click="reset">重置</a>
                                                </div>
                                            </template>
                                            <template #content>
                                                <span class="ant-pro-table-column-setting-list">
                                                    <drag-container
                                                        lockAxis="y"
                                                        dragClass="ant-pro-table-drag-ghost"
                                                        dropClass="ant-pro-table-drop-ghost"
                                                        @drop="({ removedIndex, addedIndex }) => move(removedIndex, addedIndex)"
                                                    >
                                                        <template v-for="column in dynamicColumnItems" :key="column.key">
                                                            <draggable>
                                                                <div class="ant-pro-table-column-setting-list-item">
                                                                    <drag-icon />
                                                                    <a-checkbox :checked="column.checked" @change="handleColumnChange($event, column)">
                                                                        {{ column.label }}
                                                                    </a-checkbox>
                                                                </div>
                                                            </draggable>
                                                        </template>
                                                    </drag-container>
                                                </span>
                                            </template>
                                            <a-tooltip title="列设置">
                                                <setting-outlined />
                                            </a-tooltip>
                                        </a-popover>
                                    </div>
                                    <!-- <div class="ant-pro-table-list-toolbar-setting-item">
                                        <a-tooltip :title="screenState ? '退出全屏' : '全屏'">
                                            <fullscreen-outlined v-if="!screenState" @click="setFull" />
                                            <fullscreen-exit-outlined v-else @click="exitFull" />
                                        </a-tooltip>
                                    </div> -->
                                </div>
                            </div>
                        </div>
                        <a-table
                            :row-class-name="stripe"
                            :size="state.tableSize"
                            :loading="state.loading"
                            :columns="dynamicColumns"
                            :data-source="state.dataSource"
                            :pagination="{
                                'show-size-changer': true,
                                current: state.current,
                                pageSize: state.pageSize,
                                total: state.total,
                                showTotal: total => `共 ${total} 条`,
                            }"
                            ref="tableRef"
                            :getPopupContainer="_trigger => tableRef.$el"
                            :scroll="{ x: 1150, y: appStore.tableHeight }"
                            @change="handleTableChange"
                        >
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.dataIndex === 'orderNum'">
                                    <div class="order-no" @click="handleOrderClick(record)">
                                        {{ record.orderNum }}
                                        <a-tag v-if="record.orderType === 1" color="#cd201f">投诉</a-tag>
                                    </div>
                                </template>
                                <template v-if="column.dataIndex === 'orderState'">
                                    {{ statusMap[record.orderState] }}
                                </template>
                                <template v-else-if="column.dataIndex === 'orderProperty'">
                                    {{ propertyMap[record.orderProperty] }}
                                </template>
                                <template v-else-if="column.dataIndex === 'orderSource'">
                                    {{ formatSource(record.orderSource) }}
                                </template>
                                <template v-else-if="column.dataIndex === 'contact'">
                                    {{ [record.propertyOwner, record.propertyPhone].filter(Boolean).join('/') }}
                                </template>
                                <template v-else-if="column.dataIndex === 'action'">
                                    <a-button type="primary" @click="handleOrderClick(record)">
                                        {{ record.spotCheck === 1 ? '查看' : '抽检' }}
                                    </a-button>
                                </template>
                            </template>
                        </a-table>
                    </a-card>
                </div>
            </div>
        </div>
        <order-modal :model="orderModal" :visible="modalVisible" @cancel="handleEditCancel" @success="reload()" />
        <info-modal :model="orderInfoModal" :visible="infoModalVisible" @cancel="infoModalVisible = false" @success="reload()" />
    </page-container>
</template>

<script lang="ts">
    import { defineComponent, reactive, ref, watch, watchEffect, onMounted } from 'vue';
    import {
        PlusOutlined,
        ReloadOutlined,
        ColumnHeightOutlined,
        SettingOutlined,
        FullscreenOutlined,
        FullscreenExitOutlined,
        DownOutlined,
        UpOutlined,
        DownloadOutlined,
    } from '@ant-design/icons-vue';
    import { Container as DragContainer, Draggable } from '@/components/draggable';
    import { txList } from '@/api/common/proline';
    import { exportExcelCheck, pageCheck } from '@/api/order/mine-list';
    import { dictDataListByDictType } from '@/api/user/dict';
    import { getOrderClassifyPage } from '@/api/order/cate';
    import type { Pagination, TableFilters, TableColumn } from '@/typing';
    import { useFetchData } from '@/utils/hooks/useFetchData';
    import { useFullscreen } from '@/utils/hooks/useFullscreen';
    import { useTableDynamicColumns } from '@/utils/hooks/useTableColumn';
    import DragIcon from '@/components/table/drag-icon.vue';
    import OrderModal from '../mine-list/order-modal.vue';
    import InfoModal from '../mine-list/order-info-modal.vue';
    import dayjs from 'dayjs';
    import { downloadByData } from '@/utils/download';
    import { isEmpty, isUndefined } from 'lodash-es';
    import { options, statusMap, propertyMap, typeMap, spotCheckMap } from '../mine-list/common';
    import { useAppStore } from '@/store/app';
    const appStore = useAppStore();

    export default defineComponent({
        name: 'TableList',
        setup() {
            const tableRef = ref();
            const exportLoading = ref<boolean>(false);
            const expand = ref<boolean>(false);
            const dictData = reactive<any>({});

            const filteredInfoMap = ref();
            const queryParams = reactive<any>({
                orderTime: [],
            });
            const fetchDataContext = reactive<any>({
                current: 1,
                pageSize: 10,
                tableSize: 'middle', // 'default' | 'middle' | 'small'
                stripe: false,
                executeImmediately: false,
                requestParams: { ...queryParams },
            });
            watch(
                filteredInfoMap,
                () => {
                    // queryParams.status = filteredInfoMap.value?.status;
                    // fetchDataContext.requestParams = { ...queryParams };
                },
                { immediate: true },
            );
            const mergedColumns = ref<TableColumn[]>([]);
            watchEffect(() => {
                const baseColumns: TableColumn[] = [
                    {
                        title: '工单编号',
                        dataIndex: 'orderNum',
                        width: 180,
                        ellipsis: true,
                        fixed: 'left',
                    },
                    {
                        title: '项目名称',
                        dataIndex: 'projectName',
                        width: 120,
                        ellipsis: true,
                    },
                    {
                        title: '房产号',
                        dataIndex: 'propertyRoom',
                        width: 150,
                        ellipsis: true,
                    },
                    {
                        title: '客户姓名/电话',
                        dataIndex: 'contact',
                        width: 180,
                        ellipsis: true,
                    },
                    {
                        title: '工单类型',
                        dataIndex: 'orderType',
                        width: 90,
                        ellipsis: true,
                        customRender: ({ text }) => typeMap[text],
                    },
                    {
                        title: '工单分类',
                        dataIndex: 'orderClassifyName',
                        width: 90,
                        ellipsis: true,
                    },
                    {
                        title: '责任条线',
                        dataIndex: 'orderProfessionalLine',
                        width: 120,
                        ellipsis: true,
                        customRender: ({ text }) => (text ? text.replace('品质', '') : ''),
                    },
                    {
                        title: '提报时间',
                        dataIndex: 'orderTime',
                        width: 160,
                        ellipsis: true,
                    },
                    {
                        title: '工单内容',
                        dataIndex: 'content',
                        width: 180,
                        ellipsis: true,
                    },
                ];
                const lastColumns: TableColumn[] = [
                    {
                        title: '工单状态',
                        dataIndex: 'orderState',
                        width: 90,
                        ellipsis: true,
                    },
                    {
                        title: '工单来源',
                        dataIndex: 'orderSource',
                        width: 100,
                        ellipsis: true,
                    },
                    {
                        title: '当前负责人',
                        dataIndex: 'orderChargePerson',
                        width: 110,
                        ellipsis: true,
                    },
                    {
                        title: '接单时间',
                        dataIndex: 'taskingTime',
                        width: 160,
                        ellipsis: true,
                    },
                    {
                        title: '关单时间',
                        dataIndex: 'orderFinishTime',
                        width: 160,
                        ellipsis: true,
                    },
                    {
                        title: '责任归属',
                        dataIndex: 'orderChargeCompany',
                        width: 90,
                        customRender: ({ text }) => (text ? '地产' : '物业'),
                    },
                    {
                        title: '评价得分',
                        dataIndex: 'score',
                        width: 90,
                    },
                    {
                        title: '抽检状态',
                        dataIndex: 'spotCheck',
                        width: 90,
                        customRender: ({ text }) => spotCheckMap[text],
                    },
                    {
                        title: '操作',
                        dataIndex: 'action',
                        width: 80,
                        fixed: 'right',
                    },
                ];
                mergedColumns.value = [...baseColumns, ...lastColumns];
            });
            const needRowIndex = ref(false);
            const {
                state: columnState,
                dynamicColumns,
                dynamicColumnItems,
                handleColumnAllClick,
                handleColumnChange,
                reset,
                move,
            } = useTableDynamicColumns(mergedColumns.value, { needRowIndex });

            const [elRef, screenState, { setFull, exitFull }] = useFullscreen();

            const { stripe, context: state, reload } = useFetchData(pageCheck, fetchDataContext);

            onMounted(() => {
                Promise.all([
                    dictDataListByDictType({
                        dictType: 'order_ascription',
                    }),
                    txList(),
                    getOrderClassifyPage({
                        current: 1,
                        size: 10000,
                    }),
                ]).then(res => {
                    const [xmytData, txData, cateData] = res;
                    dictData.xmytData = xmytData.data;
                    dictData.cateData = cateData.data;
                    dictData.txData = txData.data;
                });
            });

            const formatSource = (source: string) => {
                if (isUndefined(source) || isEmpty(dictData.xmytData)) return '';
                return dictData.xmytData.find(item => item.value === source)?.label || '';
            };

            const handleTreeCheck = (
                checkedKeys,
                e: any,
                // e: { checked: boolean; checkedNodes; node; event },
            ) => {
                console.log(checkedKeys, e);
                queryParams.projectCode = checkedKeys;
                fetchDataContext.executeImmediately = true;
                handleSearch();
            };

            const handleTableChange = ({ current, pageSize }: Pagination, filters?: TableFilters) => {
                filteredInfoMap.value = filters;
                fetchDataContext.current = current;
                fetchDataContext.pageSize = pageSize;
            };

            const handleSearch = () => {
                fetchDataContext.current = 1;
                const { orderTime = [], ...params } = queryParams;

                if (!isEmpty(orderTime) && orderTime.length === 2) {
                    params.orderTimeStart = dayjs(orderTime[0]).format('YYYY-MM-DD') + ' 00:00:00';
                    params.orderTimeEnd = dayjs(orderTime[1]).format('YYYY-MM-DD') + ' 23:59:59';
                }

                fetchDataContext.requestParams = { ...params };
            };
            const handleReset = () => {
                Object.keys(queryParams).forEach(key => {
                    delete queryParams[key];
                });
                queryParams.orderTime = [];
                handleSearch();
            };

            // modal
            const modalVisible = ref(false);
            const infoModalVisible = ref(false);
            const orderModal = reactive<any>({});
            const orderInfoModal = reactive<any>({});
            const handleExport = () => {
                exportLoading.value = true;
                exportExcelCheck({
                    ...fetchDataContext.requestParams,
                    size: 1000000,
                })
                    .then(res => {
                        console.log(res);
                        downloadByData(res, '抽检工单.xlsx');
                    })
                    .finally(() => {
                        exportLoading.value = false;
                    });
            };

            const handleEdit = (data: any) => {
                Object.assign(orderModal, {
                    id: data.id,
                });
                modalVisible.value = true;
            };

            const handleEditCancel = () => {
                Object.keys(orderModal).forEach(key => {
                    delete orderModal[key];
                });
                modalVisible.value = false;
            };

            const handleOrderClick = row => {
                Object.keys(orderInfoModal).forEach(key => {
                    delete orderInfoModal[key];
                });
                Object.assign(orderInfoModal, row);
                infoModalVisible.value = true;
            };

            return {
                appStore,
                dictData,
                reload,
                state,
                stripe,
                columnState,
                dynamicColumns,
                dynamicColumnItems,
                options,
                queryParams,
                handleSearch,
                handleReset,
                // fullscreen
                elRef,
                screenState,
                setFull,
                exitFull,

                handleTableChange,

                handleColumnChange,
                handleColumnAllClick,
                reset,
                move,

                // modal controls
                modalVisible,
                infoModalVisible,
                orderModal,
                orderInfoModal,
                handleEdit,

                tableRef,
                fetchDataContext,
                handleTreeCheck,
                handleEditCancel,
                handleExport,

                exportLoading,
                statusMap,
                propertyMap,
                typeMap,
                spotCheckMap,
                formatSource,
                expand,

                handleOrderClick,
            };
        },
        components: {
            DragIcon,
            PlusOutlined,
            ReloadOutlined,
            ColumnHeightOutlined,
            SettingOutlined,
            FullscreenOutlined,
            FullscreenExitOutlined,
            DownOutlined,
            UpOutlined,
            DownloadOutlined,
            Draggable,
            DragContainer,
            OrderModal,
            InfoModal,
        },
    });
</script>

<style lang="less" scoped>
    @import '../common.less';
</style>
